package com.shop.common.exception;

import com.alibaba.fastjson.JSONObject;
import com.shop.commom.utils.JSONResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestControllerAdvice
public class GloableException {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @ExceptionHandler(Exception.class)
    public JSONResult handler(Exception exception){
        logger.info(exception.getMessage(),exception);
        return JSONResult.error("未知异常");
    }

    @ExceptionHandler(IllegalArgumentException.class)
    public JSONResult handler(IllegalArgumentException exception){
        return JSONResult.error(exception.getMessage());
    }

    @ExceptionHandler(MyException.class)
    public JSONResult handler(MyException exception){
        return JSONResult.error(exception.getMsg());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JSONResult handler(MethodArgumentNotValidException exception){
        BindingResult bindingResult = exception.getBindingResult();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        Map map = new HashMap();
        fieldErrors.forEach(item -> {
            map.put(item.getField(),item.getDefaultMessage());
        });
        return JSONResult.error(JSONObject.toJSONString(map));
    }

}
